﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;
using LynxWiki.Parser;
using LynxWiki.DomainModel;
using LynxWiki.Repository;

namespace LynxWikiSyndication
{
    public static class GetFeedItems
    {
        public static List<SyndicationItem> GetSyndicationTopics()
        {
            WikiRoot.RootDirectory = ConfigurationManager.AppSettings["WikiRoot"];
            WikiRoot.SiteUrl = ConfigurationManager.AppSettings["WebSiteUrl"];
            WikiRoot.EmoticonUrl = ConfigurationManager.AppSettings["EmoticonUrl"];
            WikiRoot.HostWikiPath = ConfigurationManager.AppSettings["HostWikiPath"];
            WikiRoot.MaxAttachmentSize = ConfigurationManager.AppSettings["MaxAttachmentSize"];
            WikiDirectoryRepository wikiDirRep = new WikiDirectoryRepository(Path.Combine(ConfigurationManager.AppSettings["HostWikiPath"] + WikiRoot.RootDirectory));
            List<FileInfo> fi = wikiDirRep.GetWikiTopicFileInfoByModList(10);

            IEnumerable<WikiDirectory> wdl = wikiDirRep.GetSubDirectoryList();
            foreach (WikiDirectory dir in wdl) {
                WikiDirectoryRepository wdr = new WikiDirectoryRepository(Path.Combine(ConfigurationManager.AppSettings["HostWikiPath"] + WikiRoot.RootDirectory, dir.DirectoryName));
                List<FileInfo> sfi = wdr.GetWikiTopicFileInfoByModList(10);
                if (sfi != null) {
                    fi = fi.Union(sfi).ToList();
                }
            }
            List<FileInfo> sel = fi.OrderByDescending(f => f.LastWriteTime).Take(10).ToList();
            List<SyndicationItem> lsi = new List<SyndicationItem>();
            foreach (FileInfo item in sel) {
                WikiTopicRepository wtr = new WikiTopicRepository(item.DirectoryName);
                TopicVersion tv = wtr.GetCurrentVersion(item.Name.Substring(0, item.Name.IndexOf("__current.xml")));
                if (!string.IsNullOrEmpty(tv.WikiDir)) {
                    if (tv.UserReadAccess(HttpContext.Current.User)) {
                        SyndicationItem si = new SyndicationItem(tv.TopicName,
                            SyndicationContent.CreateHtmlContent(tv.HtmlText.Replace(@"\" + WikiRoot.RootDirectory, "/" + WikiRoot.RootDirectory.Replace(@"\", "/"))),
                            new Uri(ConfigurationManager.AppSettings["WebSiteUrl"] + "WikiTopic/Page/" + tv.WikiDir + "/" + tv.TopicName),
                            tv.TopicName + string.Format("{0:0000}", tv.Version),
                            tv.CreatedOn);
                        if (tv.Properties.ContainsKey("Summary")) {
                            si.Summary = new TextSyndicationContent(tv.Properties["Summary"]);
                        }
                        lsi.Add(si);
                    }
                }
                else {
                    if (tv.UserReadAccess(HttpContext.Current.User)) {
                        SyndicationItem si = new SyndicationItem(tv.TopicName,
                            SyndicationContent.CreateHtmlContent(tv.HtmlText.Replace(@"\" + WikiRoot.RootDirectory, "/" + WikiRoot.RootDirectory.Replace(@"\", "/"))),
                            new Uri(ConfigurationManager.AppSettings["WebSiteUrl"] + "WikiTopic/Page/" + tv.WikiDir + "/" + tv.TopicName),
                            tv.TopicName + string.Format("{0:0000}", tv.Version),
                            tv.CreatedOn);
                        if (tv.Properties.ContainsKey("Summary")) {
                            si.Summary = new TextSyndicationContent(tv.Properties["Summary"]);
                        }
                        lsi.Add(si);
                    }
                }
            }
            return lsi;
        }

        public static HttpResponseMessage GetResponse(SyndicationFeedFormatter fmtr)
        {
            MemoryStream memStrm = new MemoryStream();

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            settings.ConformanceLevel = ConformanceLevel.Document;
            settings.Indent = true;

            using (XmlWriter xmlWrtr = XmlWriter.Create(memStrm, settings)) {
                fmtr.WriteTo(xmlWrtr);
                xmlWrtr.Flush();
                xmlWrtr.Close();
            }

            memStrm.Seek(0, SeekOrigin.Begin);

            HttpResponseMessage hRespMsg = new HttpResponseMessage();

            hRespMsg.Content = new StreamContent(memStrm);
            hRespMsg.Content.Headers.ContentLength = memStrm.Length;

            return hRespMsg;

        }
    }
}